package com.zhc.tools.common.util;

import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;


/**
 * 
 * @author zhc
 *  远程调用接口方法
 */
public class HttpClientUtil {

	private final static Log logger = LogFactory.getLog(HttpClientUtil.class);
	
	/**
	 * file upload
	 * Map<String, Object> paramMap = new HashMap<String, Object>();
	 * paramMap.put("systemKey", systemKey);
	 * paramMap.put("file", new InputStreamBody(fileStore.getInputStream(), fileStore.getOriginalName()));
	 * body = HttpUtil.postObj(url, null, paramMap, 30);
	 * 
	 * @param url
	 * @param mediaType
	 * @param map
	 * @param timeout
	 * @return
	 * @throws Exception
	 */
	public static String postObj(String url, String mediaType, Map<String, Object> map, int timeout) throws Exception{
		String r = null;
		CloseableHttpClient client = HttpClients.createDefault();
		RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).build();
		
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.setCharset(Charset.forName("UTF-8"));//设置请求的编码格式
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式
		
		for (String key : map.keySet()) {
			Object obj = map.get(key);
			if (obj instanceof ContentBody) {
				builder.addPart(key, (ContentBody)obj);
			} else if (obj instanceof String) {
				builder.addTextBody(key, (String)obj);
			} else if (obj instanceof byte[]) {
				builder.addBinaryBody(key, (byte[])obj);
			} else if (obj instanceof File) {
				builder.addBinaryBody(key, (File)obj);
			} else if (obj instanceof InputStream) {
				builder.addBinaryBody(key, (InputStream)obj);
			} else {
				// nothing todo
			}
		}
		
		// 生成 HTTP POST 实体 
		HttpEntity entity = builder.build(); 	
		
		HttpPost post = new HttpPost(url);
		post.setEntity(entity);
		post.setConfig(config);
		
		CloseableHttpResponse response = client.execute(post);
		try {
			int statusCode = response.getStatusLine().getStatusCode();
			logger.info("statusCode::" + statusCode);
			HttpEntity e = response.getEntity();
			r = EntityUtils.toString(e, "UTF-8");
			logger.info("r:#" + r);
		} finally {
			response.close();
		}
		return r;
	}

	/**
	 * post请求
	 * @param url 请求的地址
	 * @param mediaType 请求的数据协议
	 * @param content 传送的报文
	 * @return
	 * @throws Exception
	 */
	public static String postForObject(String url,String mediaType,String content) throws Exception{
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,5000);//设置超时时间
		post.setHeader("Content-Type", mediaType);
		String retStr="";
	    //这种单独传字符串进去
		StringEntity reqEntity = new StringEntity(content,"utf-8");
		post.setEntity(reqEntity);
		HttpResponse response = client.execute(post); 
		int code = response.getStatusLine().getStatusCode();
		if(code==200){
			  HttpEntity entity = response.getEntity();
			  retStr=EntityUtils.toString(entity);
		}else
			throw new Exception(String.valueOf(code));
		return retStr;
	}
	/**
	 * post请求
	 * @param url 请求的地址
	 * @param mediaType 请求的数据协议
	 * @param map 参数结合
	 * @return
	 * @throws Exception
	 */
	public static String postForObject(String url,String mediaType, Map<String,String> map) throws Exception{
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		if(mediaType!=null){
			post.setHeader("Content-Type", mediaType);
		}
		String retStr="";
		List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		HttpEntity httpentity = new UrlEncodedFormEntity(formParams, "UTF-8");
	    //这种单独传字符串进去
		post.setEntity(httpentity);
		HttpResponse response = client.execute(post); 
		int code = response.getStatusLine().getStatusCode();
		if(code==200){
			  HttpEntity entity = response.getEntity();
			  retStr=EntityUtils.toString(entity,"UTF-8");
		}else
			throw new Exception(String.valueOf(code));
		return retStr;
	}
	/**
	 * 
	 * @param url 请求的URL
	 * @param mediaType 请求的数据类型
	 * @param map 请求的参数结合
	 * @return
	 * @throws Exception
	 */
	public static String getForObject(String url,Map<String,String> map) throws Exception{
		StringBuffer sb = new StringBuffer(url);
		if(map!=null){
			sb.append("?");
			 int a=0;
			 for (Map.Entry<String, String> entry : map.entrySet()) {
				   if(a!=0){
					  sb.append("&");
				   }
				   sb.append(entry.getKey());
				   sb.append("=");
				   sb.append(entry.getValue());
				   a++;
			 }
		}
		URL url1 = new URL(url);
		URI uri = new URI(url1.getProtocol(), url1.getHost() + ":" +(url1.getPort()==-1?"":url1.getPort()), url1.getPath(), url1.getQuery(), null);
		//得到浏览器
		HttpClient client = new DefaultHttpClient();
		//指定请求方式
		HttpGet  get = new HttpGet(uri);
		String retStr="";
		//执行请求
		HttpResponse response = client.execute(get); 
		int code = response.getStatusLine().getStatusCode();
		//判断请求是否成功
		if(code==200){
		   //获取返回的实体
		   HttpEntity entity = response.getEntity();
		   //获取返回的内容
		   retStr=EntityUtils.toString(entity,"UTF-8");
		}else
			 throw new Exception(String.valueOf(code));
		return retStr;
	}
	
	
}
